const url = require('url');

/* 封装改变res, 绑定res.send */
function changeRes(res){
    res.send = function (data) {
        res.writeHead(200, {'Content-Type':'text/html;charset="utf8"'});
        res.end(data);
    }
}

/* 暴露的模块 */
const Serve = function () {
    let G = this;
    /* 处理get和post请求 */
    this._get = {};
    this._post = {};

    let app = function (req,res) {
        changeRes(res);
        /* 获取路由 */
        let pathname = url.parse(req.url).pathname;
        if(!pathname.endsWith('/')){
            pathname = pathname + '/';
        }

        /* 获取 get post 请求 */
        let method = req.method.toLowerCase();
        if(G['_'+method][pathname]){
            if(method === 'post'){
                let strPost = '';
                req.on('data',function (chunk) {
                    strPost += chunk;
                });
                req.on('end',function (err,chunk) {
                    req.body = strPost;
                    G['_'+method][pathname](req,res);
                })
            }else{
                G['_' + method][pathname](req,res);
            }
        }else{
            res.end('no router');
        }
    };

    app.get = function (string, callback) {
        if(!string.endsWidth('/')){
            string = string + '/';
        }
        if(!string.startsWith('/')){
            string = '/' + string;
        }
        G._get[string] = callback;
    };
    app.post = function (string,callback) {
        if(!string.endsWidth('/')){
            string = string + '/';
        }
        if(!string.startsWith('/')){
            string = '/' + string;
        }
        G._post[string] = callback;
    };

    return app;
};

module.exports = Serve();